import json,os
import logging

from flask import Blueprint, request, jsonify, render_template, redirect, url_for

from applications.common.utils.http import fail_api, success_api, table_api
from applications.common.utils.rights import authorize
from mod.fun import tconf, rmconf

dir_path = os.path.dirname(os.path.realpath(__file__)).replace("\\", "/")

bp = Blueprint('dev_conf', __name__, url_prefix='/conf')

plugindir = 'plugins'

@bp.route('/', methods=['GET'])
def index():
    logging.warn('进入配置管理页面')
    logging.log(20, '进入配置管理页面')
    dlist = os.listdir(plugindir)
    pluglist = []

    for i in dlist:
        if i in ['__pycache__']:
            continue
        fpath = os.path.join(plugindir, i)
        if os.path.isdir(fpath):
            pluglist.append(i)
    return render_template('conf/index.html', pluglist=pluglist)

@bp.route('/ajax_getjson', methods=['POST'])
def ajax_getjson():
    app = request.form.get('app')
    if not app:
        return jsonify({
            'result': 'no',
            'msg': 'app参数不能为空'
        })
    fpath = os.path.join(plugindir, app, 'config')
    jsonfile = os.path.join(fpath, 'config.json')
    if os.path.exists(jsonfile):
        with open(jsonfile, 'r', encoding='utf-8') as f:
            jsonconf = json.load(f)
    else:
        jsonconf = {}
    if jsonconf:
        jdata = {'__sys__':{}}
        for k in jsonconf.keys():
            if '_' in k:
                tmp = k.split('_')
                if tmp[0] not in jdata:
                    jdata[tmp[0]] = {}
                jdata[tmp[0]][k] = jsonconf[k]
            else:
                jdata['__sys__'][k] = jsonconf[k]
        # print(jdata)
        return render_template('conf/ajax_json.html',jsonconf=jdata)
    return ''


@bp.route('/ajax_savejson', methods=['POST'])
def ajax_savejson():
    data = request.form
    if data['app'] == '':
        return jsonify({
            'result': 'no',
            'msg': 'app参数不能为空'
        })
    fpath = os.path.join(plugindir, data['app'], 'config')
    jsonfile = os.path.join(fpath, 'config.json')
    if os.path.exists(os.path.join(plugindir,data['app'])) and not os.path.exists(fpath):
        os.makedirs(fpath)
    wdata = {}
    key = data.getlist('key[]')
    des = data.getlist('des[]')
    val = data.getlist('val[]')
    name = data.getlist('name[]')

    for k,v in enumerate(key):
        wdata[v] = {
            'key':v,
            'des':des[k],
            'val':val[k],
            'name':name[k]
        }
    with open(jsonfile, 'w', encoding='utf-8') as f:
        json.dump(wdata, f, ensure_ascii=False, indent=4)
    # 返回配置首页
    return redirect(url_for('dev.dev_conf.index'))
